package solutions.leetcode.hard;

import solutions.lib.BaseSolution;

/**
 * @author lizhidong
 * <a href="https://leetcode-cn.com/problems/integer-to-english-words/">273. 整数转换英文表示</a>
 */
public class Solution273 extends BaseSolution {

    public String numberToWords(int num) {
        if (num == 0) {
            return "Zero";
        }
        String[] floorStr = new String[] {
                "Thousand",
                "Million",
                "Billion",
        };
        String hundred = "Hundred";
        String[] bitStr = new String[] {
                "One",
                "Two",
                "Three",
                "Four",
                "Five",
                "Six",
                "Seven",
                "Eight",
                "Nine",
        };
        String[] tenStr = new String[] {
                "Ten",
                "Eleven",
                "Twelve",
                "Thirteen",
                "Fourteen",
                "Fifteen",
                "Sixteen",
                "Seventeen",
                "Eighteen",
                "Nineteen"
        };
        String[] bit2Str = new String[] {
                "Ten",
                "Twenty",
                "Thirty",
                "Fourty",
                "Fifty",
                "Sixty",
                "Seventy",
                "Eighty",
                "Ninety"
        };
        StringBuilder rst = new StringBuilder();
        int floor = -1;
        while (num != 0) {
            int val = num % 1000;
            num /= 1000;
            if (val > 0 && floor >= 0) {
                insert(rst, floorStr[floor]);
            }
            floor++;
            if (val == 0) {
                continue;
            }
            int ten = val % 100;
            if (ten > 0) {
                int t = ten / 10;
                int o = ten % 10;
                if (t != 1) {
                    if (o != 0) {
                        insert(rst, bitStr[o - 1]);
                    }
                    if (t != 0) {
                        insert(rst, bit2Str[t - 1]);
                    }
                } else {
                    insert(rst, tenStr[o]);
                }
            }
            int hun = val / 100;
            if (hun > 0) {
                insert(rst, hundred);
                insert(rst, bitStr[hun - 1]);
            }
        }
        return rst.toString();
    }

    private void insert(StringBuilder sb, Object val) {
        if (sb.length() != 0) {
            sb.insert(0, " ");
        }
        sb.insert(0, val);
    }

    public static void main(String[] args) {
        Solution273 solution = new Solution273();
        System.out.println(solution.numberToWords(1000));
    }
}